using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using UniversalAdmin.Application.Commands;
using UniversalAdmin.Application.Dto;
using UniversalAdmin.Application.Services;
using UniversalAdmin.Shared.Enums;
using UniversalAdmin.Api.Filters;

[ApiController]
[Route("api/roles")]
[Authorize]
public class RolesController : ControllerBase
{
    private readonly IAppRoleServices _roleService;
    public RolesController(IAppRoleServices roleService) { _roleService = roleService; }

    // 分页+搜索
    [HttpGet]
    [RequirePermission("role.view")] // 需要查看角色权限
    public async Task<ApiResult> Get([FromQuery] int? page = null, [FromQuery] int? size = null, [FromQuery] string? search = null)
    {
        if (page.HasValue && size.HasValue)
        {
            var result = await _roleService.GetPagedAsync(new PagedQuery { Page = page.Value, Size = size.Value, Search = search });
            return new ApiResult { Code = result.Code, Message = result.Message, Data = result.Data, Timestamp = result.Timestamp };
        }
        else
        {
            var result = await _roleService.GetAllAsync(search);
            return new ApiResult { Code = result.Code, Message = result.Message, Data = result.Data, Timestamp = result.Timestamp };
        }
    }

    // 获取单个角色
    [HttpGet("{id}")]
    [RequirePermission("role.view")] // 需要查看角色权限
    public async Task<ApiResult<RoleDto>> GetById(Guid id)
        => await _roleService.GetByIdAsync(id);

            // 创建角色
        [HttpPost]
        [RequirePermission("role.create")]
        public async Task<ApiResult> Create([FromBody] CreateRoleDto dto)
    {
        return await _roleService.CreateAsync(dto);
    }

    // 更新角色
    [HttpPut("{id}")]
    [RequirePermission("role.edit")] // 需要编辑角色权限
    public async Task<ApiResult> Update(Guid id, [FromBody] UpdateRoleDto dto)
        => await _roleService.UpdateAsync(id, dto);

    // 删除角色
    [HttpDelete("{id}")]
    [RequirePermission("role.delete")] // 需要删除角色权限
    public async Task<ApiResult> Delete(Guid id)
        => await _roleService.DeleteAsync(id);

    // 启用角色
    [HttpPut("{id}/enable")]
    [RequirePermission("role.edit")] // 需要编辑角色权限
    public async Task<ApiResult> EnableRole(Guid id)
    {
        return await _roleService.EnableRole(id);
    }

    // 禁用角色
    [HttpPut("{id}/disable")]
    [RequirePermission("role.edit")] // 需要编辑角色权限
    public async Task<ApiResult> DisableRole(Guid id)
    {
        return await _roleService.DisableRole(id);
    }

    // 分配权限
    [HttpPost("{id}/permissions")]
    [RequirePermission("role.manage")]
    public async Task<ApiResult> AssignPermissions(Guid id, [FromBody] AssignRolePermissionsDto dto)
    {
        return await _roleService.AssignPermissions(id, dto.PermissionIds);
    }
} 